<template>
  <view class="container">
    <!-- 头部导航 -->
    <!-- 医院信息卡片 -->
    <view class="hospital-card">
      <view class="hospital-info">
        <image
          class="hospital-img"
          :src="hospitalInfo.hospitalImg"
          mode="aspectFit"></image>
        <view class="hospital-detail">
          <view class="hospital-name">{{ hospitalInfo.hospitalName }}</view>
          <view class="tag-list">
            <text class="tag hospital-level">{{ hospitalInfo.hospitalLevel }}</text>
            <text class="tag hospital-type">综合医院</text>
          </view>
          <view class="address">
            <text>地址：{{ hospitalInfo.hospitalAddress }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 服务选择卡片（核心功能区） -->
    <view class="order-card">
      <!-- 科室选择（下拉选择，从接口获取） -->
      <view class="form-item">
        <text class="form-label">选择科室：</text>
        <picker
          class="time-picker"
          mode="selector"
          :range="departments"
          v-model="selectedDepartmentIndex"
          @change="handleDepartmentChange"
          :disabled="!departments.length">
          <view class="picker-display">
            {{ selectedDepartment ? selectedDepartment : "请选择科室" }}
          </view>
        </picker>
      </view>

      <!-- 套餐选择（下拉选择，动态获取，依赖科室选择） -->
      <view class="form-item" v-if="selectedDepartment">
        <text class="form-label">选择套餐：</text>
        <picker
          class="time-picker"
          mode="selector"
          :range="packageTypes"
          v-model="selectedPackageIndex"
          @change="handlePkgChange"
          :disabled="!packageTypes.length">
          <view class="picker-display">
            {{ selectedPackageType ? selectedPackageType : "请选择套餐类型" }}
          </view>
        </picker>
      </view>

      <!-- 患者状态单选组（根据选中套餐动态渲染） -->
      <view class="form-item" v-if="selectedPackageType && selectedDepartment">
        <text class="form-label">患者状态：</text>
        <view class="radio-group">
          <view
            class="radio-item"
            v-for="(status, index) in currentPatientStatusList"
            :key="index"
            @click="selectStatus(status)"
            :class="{ 'radio-checked': selectedPatientStatus === status }">
            <view class="radio-icon">
              <image
                src="../../static/tab_select_have.png"
                mode="aspectFit"
                v-if="selectedPatientStatus === status"></image>
            </view>
            <text class="radio-text">{{ status }}</text>
          </view>
        </view>
      </view>

      <!-- 服务时间下拉选择（根据套餐+患者状态动态渲染） -->
      <view class="form-item" v-if="selectedPatientStatus && selectedDepartment">
        <text class="form-label">服务时间：</text>
        <picker
          class="time-picker"
          mode="selector"
          :range="currentTimeOptions"
          v-model="selectedTimeIndex"
          @change="handleTimeChange"
          :disabled="!currentTimeOptions.length">
          <view class="picker-display">
            {{ selectedTime ? selectedTime : "请选择服务时间" }}
          </view>
        </picker>
      </view>

      <!-- 动态金额显示 -->
      <view class="form-item amount-item" v-if="selectedTime && selectedDepartment">
        <text class="form-label">服务金额：</text>
        <text class="amount-text">¥{{ currentAmount }}</text>
      </view>

      <!-- 确认按钮（只有三者都选中才启用） -->
      <button
        class="confirm-btn"
        @click="handleConfirm(item)"
        :disabled="
          !selectedPackageType || !selectedPatientStatus || !selectedTime || !selectedDepartment
        ">
        确定
      </button>
    </view>

    <!-- 重点科室卡片 -->
    <view class="section-card">
      <view class="section-title">重点科室：</view>
      <view class="department-list">
        <text class="department-item">
          {{ hospitalInfo.hospitalDepartments}}
        </text>
      </view>
    </view>

    <!-- 医院简介内容 -->
    <view class="section-card">
      <view class="section-title">医院简介：</view>
      <view class="intro-text">
        {{ hospitalInfo.hospitalIntroduce || "暂无医院简介信息" }}
      </view>

      <view class="section-title">学科实力:</view>
      <view class="intro-item">
        <text class="item-text">
          {{ hospitalInfo.hospitalSubject || "暂无相关信息" }}
        </text>
      </view>

      <view class="section-title">医疗技术:</view>
      <view class="intro-item">
        <text class="item-text">
          {{ hospitalInfo.hospitalSkill || "暂无相关信息" }}
        </text>
      </view>

      <view class="section-title">科室设置:</view>
      <view class="intro-item">
        <text class="item-text">
          {{ hospitalInfo.hospitalInstall || "暂无相关信息" }}
        </text>
      </view>

      <view class="section-title">科研教学:</view>
      <view class="intro-item">
        <text class="item-text">
          {{ hospitalInfo.hospitalTeach || "暂无相关信息" }}
        </text>
      </view>

      <view class="section-title">医院设备:</view>
      <view class="intro-item">
        <text class="item-text">
          {{ hospitalInfo.hospitalDevice || "暂无相关信息" }}
        </text>
      </view>
    </view>
  </view>
</template>

<script>
import { getNurseHospitalInfo, getVisitServe } from "../../common/api/index.js";
import { getToken } from "@/utils/auth.js";
export default {
  data() {
    return {
      token: getToken(),
      hospitalInfo: {}, // 医院信息
      hospitalName: "", // 医院名称

      // 接口原始数据
      serverData: [], // 从getVisitServe获取的nurseServersList数据
      serverCode: "",
      serverResponseData: [], // 保存完整的接口响应数据

      // 科室相关
      departments: [], // 科室列表
      selectedDepartmentIndex: -1, // 选中的科室索引
      selectedDepartment: "", // 选中的科室

      // 动态解析后的数据
      packageTypes: [], // 套餐类型列表（例：["一对一套餐", "一对多套餐"]）
      patientStatusGroups: {}, // 按套餐分组的患者状态：{ "一对一套餐": ["自理", "半自理", ...], ... }
      timePriceMap: {}, // 套餐-患者状态对应的时间价格：{ "一对一套餐-自理": [{time: "12小时", price: 180}, ...], ... }
      dynamicPriceMap: {}, // 最终价格映射：{ "套餐-患者状态-服务时间": 金额 }

      // 选中状态
      selectedPackageIndex: -1, // 选中的套餐索引
      selectedPackageType: "", // 选中的套餐类型（例："一对一套餐"）
      selectedPatientStatus: "", // 选中的患者状态（例："自理"）
      selectedTimeIndex: 0, // 选中的服务时间索引
      selectedTime: "", // 选中的服务时间（例："12小时"）
      hospitalId: "", // 选中医院ID
    };
  },
  onLoad(opt) {
    this.hospitalName = opt.hospitalName;
    this.hospitalId = opt.id;
    // 获取医院信息
    getNurseHospitalInfo({ hospitalName: this.hospitalName }).then((res) => {
      console.log("返回医院信息", res);
      if (res.data.data) {
        this.hospitalInfo = res.data.data;
      }
    });
    // 获取套餐列表数据并解析
    this.fetchAndParseServerData();
  },
  computed: {
    // 当前选中套餐对应的患者状态列表
    currentPatientStatusList() {
      return this.patientStatusGroups[this.selectedPackageType] || [];
    },
    // 当前选中套餐+患者状态对应的服务时间列表
    currentTimeOptions() {
      const key = `${this.selectedPackageType}-${this.selectedPatientStatus}`;
      return this.timePriceMap[key]?.map((item) => item.time) || [];
    },
    // 实时计算当前选中组合的金额
    currentAmount() {
      if (
        !this.selectedPackageType ||
        !this.selectedPatientStatus ||
        !this.selectedTime
      ) {
        return 0;
      }
      const key = `${this.selectedPackageType}-${this.selectedPatientStatus}-${this.selectedTime}`;
      return this.dynamicPriceMap[key] || 0;
    },
  },
  methods: {
    goBack() {
      uni.navigateBack({ delta: 1 });
    },
    showMore() {
      uni.showActionSheet({
        itemList: ["收藏", "投诉", "分享给朋友"],
        success(res) {
          console.log(res.tapIndex);
        },
      });
    },
    share() {
      uni.showShareMenu({
        withShareTicket: true,
        menus: ["shareAppMessage", "shareTimeline"],
      });
    },

    // 获取并解析套餐列表数据
    fetchAndParseServerData() {
      getVisitServe({hospitalId: this.hospitalId})
        .then((res) => {
          console.log("套餐接口返回数据", res);
          if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
            // 保存完整响应数据
            this.serverResponseData = res.data.data;
            
            // 提取科室列表
            this.departments = res.data.data.map(item => item.departmentName);
            
            // 如果有科室数据，默认选中第一个科室
            if (this.departments.length > 0) {
              this.selectedDepartmentIndex = 0;
              this.selectedDepartment = this.departments[0];
              
              // 根据选中的科室获取对应的服务数据
              this.updateServerDataByDepartment();
            }
          } else {
            uni.showToast({ title: "当前医院无套餐", icon: "none" });
          }
        })
        .catch((err) => {
          console.error("获取套餐数据异常", err);
          uni.showToast({ title: "网络错误，无法获取套餐", icon: "none" });
        });
    },

    // 根据选中的科室更新服务数据
    updateServerDataByDepartment() {
      // 找到当前选中科室的数据
      const departmentData = this.serverResponseData.find(
        item => item.departmentName === this.selectedDepartment
      );
      
      if (departmentData && departmentData.nurseServerListVOList && departmentData.nurseServerListVOList.length > 0) {
        // 获取该科室下的服务列表
        this.serverData = departmentData.nurseServerListVOList[0].nurseServersList || [];
        this.serverCode = departmentData.nurseServerListVOList[0].code || "";
        
        // 解析数据并设置默认套餐
        this.parseServerData();
        this.setDefaultPackage();
      } else {
        // 清空当前科室下的所有数据
        this.serverData = [];
        this.serverCode = "";
        this.packageTypes = [];
        this.patientStatusGroups = {};
        this.timePriceMap = {};
        this.dynamicPriceMap = {};
        this.resetSelections();
      }
    },

    // 重置所有选择
    resetSelections() {
      this.selectedPackageIndex = -1;
      this.selectedPackageType = "";
      this.selectedPatientStatus = "";
      this.selectedTime = "";
      this.selectedTimeIndex = 0;
    },

    // 解析套餐数据：拆分套餐类型、患者状态、服务时间、金额
    parseServerData() {
      const packageMap = {}; // 临时存储：key=套餐类型，value={ statusList: [], timePrice: {} }

      this.serverData.forEach((server) => {
        // 1. 从serverValue中提取套餐类型（一对一/一对多）和患者状态
        const packageMatch = server.serverValue.match(/(一对一|一对多)/);
        const statusMatch = server.serverValue.match(/（([^）]+)）/);

        if (!packageMatch || !statusMatch) return; // 数据格式异常则跳过

        const packageType = `${packageMatch[1]}套餐`; // 转为"一对一套餐"格式
        const patientStatus = statusMatch[1]; // 提取患者状态（例："自理"、"半自理"）

        // 2. 处理服务时间和金额（从priceList提取）
        // 假设priceList存在，如果接口结构不同需要调整
        const timePriceList = server.priceList ? server.priceList.map((item) => ({
          time: `${item.day}小时`, // 转为"12小时"格式
          price: item.price, // 金额
          day: item.day, // 原始天数，用于匹配
        })) : [];

        // 3. 初始化套餐分组数据
        if (!packageMap[packageType]) {
          packageMap[packageType] = {
            statusList: [], // 该套餐下的患者状态列表
            timePriceMap: {}, // 该套餐下：患者状态 → 时间价格列表
          };
        }

        // 4. 添加患者状态（去重）
        if (!packageMap[packageType].statusList.includes(patientStatus)) {
          packageMap[packageType].statusList.push(patientStatus);
        }

        // 5. 存储该患者状态对应的时间价格列表
        packageMap[packageType].timePriceMap[patientStatus] = timePriceList;

        // 6. 构建最终价格映射（套餐-患者状态-服务时间 → 金额）
        timePriceList.forEach((tp) => {
          const key = `${packageType}-${patientStatus}-${tp.time}`;
          this.dynamicPriceMap[key] = tp.price;
        });
      });

      // 7. 赋值给页面使用的变量
      this.packageTypes = Object.keys(packageMap); // 套餐类型列表
      // 构建患者状态分组
      this.patientStatusGroups = Object.keys(packageMap).reduce((obj, pkg) => {
        obj[pkg] = packageMap[pkg].statusList;
        return obj;
      }, {});
      // 构建时间价格分组
      Object.keys(packageMap).forEach((pkg) => {
        Object.keys(packageMap[pkg].timePriceMap).forEach((status) => {
          const key = `${pkg}-${status}`;
          this.timePriceMap[key] = packageMap[pkg].timePriceMap[status];
        });
      });
    },

    // 设置默认勾选「一对一套餐」
    setDefaultPackage() {
      // 找到"一对一套餐"在套餐列表中的索引
      const defaultIndex = this.packageTypes.findIndex(
        (pkg) => pkg === "一对一套餐"
      );
      // 存在则设置为默认选中
      if (defaultIndex !== -1) {
        this.selectedPackageIndex = defaultIndex;
        this.selectedPackageType = this.packageTypes[defaultIndex];
      }
    },

    // 科室选择变化处理
    handleDepartmentChange(e) {
      this.selectedDepartmentIndex = e.detail.value;
      this.selectedDepartment = this.departments[this.selectedDepartmentIndex];
      this.updateServerDataByDepartment();
    },

    // 套餐下拉选择变化
    handlePkgChange(e) {
      this.selectedPackageIndex = e.detail.value;
      this.selectedPackageType = this.packageTypes[this.selectedPackageIndex];
      // 重置后续选择项
      this.selectedPatientStatus = "";
      this.selectedTime = "";
      this.selectedTimeIndex = 0;
    },

    // 患者状态选择逻辑（支持选中/取消）
    selectStatus(status) {
      console.log("患者状态", status);
      
      if (this.selectedPatientStatus === status) {
        this.selectedPatientStatus = ""; // 取消选择
        this.selectedTime = ""; // 重置服务时间
        this.selectedTimeIndex = 0;
      } else {
        this.selectedPatientStatus = status; // 选中当前状态
        this.selectedTimeIndex = 0; // 重置服务时间索引
        this.selectedTime = "";
      }
    },

    // 服务时间选择变化
    handleTimeChange(e) {
      this.selectedTimeIndex = e.detail.value;
      this.selectedTime = this.currentTimeOptions[this.selectedTimeIndex] || "";
    },

    // 确定按钮：获取所有选中数据
    handleConfirm(item) {
      if (!this.token) {
        uni.showToast({
          icon: "none",
          title: "请重新登录!",
          delay: 1500,
        });
        setTimeout(() => {
          uni.setStorageSync("nav_to_index_index", 1);
          uni.reLaunch({ url: "/pages/index/index" });
        }, 2000);
        return;
      }
      // 组装选中数据（包含接口返回的serverId，便于后续提交）
      const selectedServerItem = this.serverData.find((item) => {
        const packageMatch = item.serverValue.match(/(一对一|一对多)/);
        const statusMatch = item.serverValue.match(/（([^）]+)）/);
        return (
          packageMatch &&
          statusMatch &&
          `${packageMatch[1]}套餐` === this.selectedPackageType &&
          statusMatch[1] === this.selectedPatientStatus
        );
      });
      const result = {
        department: this.selectedDepartment,//科室
        packageType: this.selectedPackageType,
        patientStatus: this.selectedPatientStatus,
        serviceTime: this.selectedTime,//服务时间
        amount: this.currentAmount,
        serverId: selectedServerItem?.serverId || "", // 接口返回的服务ID
        serverCode: this.serverCode, // 接口返回的服务编码
        hospitalName: this.hospitalInfo.hospitalName,
      };
      // 打印数据（实际项目中可提交接口）
      console.log("选中数据：", result);
      if (result.serverCode === "visit") {
        uni.navigateTo({
          url: `/nursingWorkerPages/pages/CompanionVisit/visitDetil?code=${result.serverCode}&serviceTime=${result.serviceTime}&serverId=${result.serverId}&amount=${this.currentAmount}&hospitalName=${result.hospitalName}&department=${result.department}`
        });
      } else {
        uni.navigateTo({
          url: `/nursingWorkerPages/pages/itemDetail/itemDetail?code=${result.serverCode}&serverId=${result.serverId}serviceTime=${result.serviceTime}&department=${result.department}`
        });
      }
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f5f5f5;
}

.container {
  width: 100%;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 头部导航 */
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  box-sizing: border-box;
  z-index: 100;
  border-bottom: 1rpx solid #eee;

  .back-icon {
    width: 48rpx;
    height: 48rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    image {
      width: 40rpx;
      height: 40rpx;
    }
  }

  .title {
    font-size: 34rpx;
    font-weight: 500;
  }

}

/* 医院信息卡片 */
.hospital-card {
  // margin-top: 108rpx;
  // margin: 108rpx 20rpx 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .hospital-info {
    padding: 30rpx;
    display: flex;

    .hospital-img {
      width: 160rpx;
      height: 160rpx;
      margin-right: 20rpx;
    }

    .hospital-detail {
      flex: 1;

      .hospital-name {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 16rpx;
      }

      .tag-list {
        margin-bottom: 16rpx;

        .tag {
          display: inline-block;
          padding: 4rpx 12rpx;
          font-size: 24rpx;
          border-radius: 4rpx;
          margin-right: 16rpx;
        }

        .hospital-level {
          color: #ff4d4f;
          background-color: rgba(255, 77, 79, 0.1);
        }

        .hospital-type {
          color: #1890ff;
          background-color: rgba(24, 144, 255, 0.1);
        }
      }

      .address {
        display: flex;
        align-items: center;
        font-size: 26rpx;
        color: #666;
        line-height: 1.5;

        .location-icon {
          width: 32rpx;
          height: 32rpx;
          margin-right: 8rpx;
        }
      }
    }
  }
}

/* 服务选择卡片 */
.order-card {
  margin: 0 30rpx 20rpx;
  background: white;
  padding: 30rpx;
  border-radius: 16rpx;
  margin-top: 20rpx;
}

/* 表单项目 */
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #333;
  width: 140rpx;
  text-align: right;
  margin-right: 20rpx;
}

/* 自定义单选框组 */
.radio-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 15rpx 20rpx;
  border-radius: 8rpx;
  background-color: #f9f9f9;
  cursor: pointer;
  transition: all 0.2s;

  .radio-icon {
    width: 36rpx;
    height: 36rpx;

    image {
      width: 36rpx;
      height: 36rpx;
    }
  }

  .radio-text {
    margin-left: 10rpx;
    font-size: 28rpx;
    color: #666;
  }
}

/* 选中状态样式 */
.radio-checked {
  background-color: rgba(11, 197, 174, 0.1);
  border: 2rpx solid #0bc5ae;

  .radio-icon {
    background-color: #0bc5ae;
    border-color: #0bc5ae;
  }

  .radio-text {
    color: #0bc5ae;
    font-weight: 500;
  }
}

/* 时间选择器（套餐下拉复用此样式） */
.time-picker {
  flex: 1;
  height: 60rpx;
  line-height: 30px;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
}

.time-picker:disabled {
  background-color: #fafafa;
  color: #ccc;
}

.picker-display {
  height: 100%;
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #333;
}

/* 金额显示 */
.amount-item {
  align-items: center;
}

.amount-text {
  font-size: 32rpx;
  color: #ff9900;
  font-weight: bold;
}

/* 确认按钮 */
.confirm-btn {
  width: 100%;
  height: 90rpx;
  background-color: #0bc5ae;
  color: white;
  font-size: 32rpx;
  border-radius: 12rpx;
  margin-top: 20rpx;
}

.confirm-btn:disabled {
  background-color: #b3e8e0;
  color: #fff;
}

confirm-btn::after {
  border: none;
}

/* 重点科室卡片 */
.section-card {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;

  .section-title {
    font-weight: bold;
    font-size: 30rpx;
    margin-bottom: 16rpx;
    display: block;
  }

  .department-list {
    display: flex;
    flex-wrap: wrap;
    .department-item {
      background-color: #f9f9f9;
      padding: 8rpx 16rpx;
      font-size: 26rpx;
      color: #666;
      border-radius: 6rpx;
      margin-right: 16rpx;
      margin-bottom: 16rpx;
    }
  }

  .intro-text,
  .item-text {
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
    margin-bottom: 20rpx;
    display: block;
  }
}
</style>
